package main

import (
	"fmt"
	mqtt "github.com/eclipse/paho.mqtt.golang"
	"os"
	"os/signal"
	"time"
	"tym/modbus/tcp"
	"tym/mqtt/publish"
	"tym/mqtt/subscribe"
)

var f mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
	fmt.Printf("TOPIC: %s\n", msg.Topic())
	fmt.Printf("MSG: %s\n", msg.Payload())
}

func main() {
	server := subscribe.NewMqttSubscribeServer()
	client := publish.NewMqttPublishClient()

	for {
		modbusTcpClient := tcp.NewClient("127.0.0.1:502")
		if client == nil {
			fmt.Println("无法获取tcp请求")
			break
		}
		value := modbusTcpClient.ReadHoldingRegisters(1, 0, 10)

		msg := publish.Message[[]uint16]{
			Topic: subscribe.ModbusStatusTopic,
			Data:  value,
		}
		publish.Send(msg, client)

		if err := modbusTcpClient.Close(); err != nil {
			fmt.Println(err)
		}

		time.Sleep(time.Second * 5)
	}

	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	<-c

	server.Disconnect(250)
	client.Disconnect(250)
}
